<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\SCoursewareInfo as CoursewareModel;


class DealWhiteFile implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    var $cid;
    var $file_id;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct( $file_id)
    {
        //
        $this->cid     = config('svs.white.CertificateID');
        $this->file_id = $file_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        logger('cid:'.$this->cid);
        logger('file_id:'.$this->file_id);

        $file_info = CoursewareModel::find($this->file_id);

        $fid = $file_info->file_id;

        //处理白板文件
        //1，先删除白板文件，
        if($fid > 10000) {

            $res = $this->delFile($fid);
            logger('del_res:', $res);
            CoursewareModel::where('id', $this->file_id)->update([ 
                'save_name' => '' ,
                'file_id' => '' ,
            ]);
        }
        //2，再上传文件到白板
        $res = $this->useFile($file_info);

        if($res['Result'] === true) {
            logger('use_file:', $res);
            CoursewareModel::where('id', $this->file_id)->update([ 
                'save_name' => $res['SaveName'],
                'file_id'   => $res['FileID'] 
            ]);
        }
        
        logger('upload_res:',$res);

    }

    protected function getKey()
    {

        $publicKey = config('svs.white.publicKey');

        $data = $this->cid . '+'.now()->toDateTimeString();
        openssl_public_encrypt($data, $encrypted, $publicKey);
        $encrypted = base64_encode($encrypted);
        return $encrypted;

    }

    protected function useFile($file_info)
    {
        $file_id   = request('fileId', 1);

        //白板key
        $key = $this->getKey();

        // $img_prefix = 'http://'. config('filesystems.disks.oss.bucket')
        //                     .'.'.config('filesystems.disks.oss.endpoint') . '/';
        $img_prefix = 'https://teacher.spokenglish.com/uploads/';
        logger('key:'.$key);

        return $this->uploadWhiteFile($this->cid,  $file_info->title, $img_prefix . $file_info->res_url, $key);

    }


    //上传
    protected function uploadWhiteFile($cid, $fname, $furl, $key)
    {
        //上传文件id
        $fid = time() . mt_rand(1000,9999);
        //防止文件名称重复，加盐
        $fname = uniqid().$fname.strchr($furl,'.');
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, 'http://liveapi1.bell.ai/whiteboardsdk/uploadfile');
        //设置头文件的信息作为数据流输出
        // curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);

        $content = file_get_contents($furl);
        $fpath = strpos($furl, '/');
        $path = file_put_contents($fpath, $content);

        //设置post数据
        $post_data = array(
            "CertificateID"  => $cid,
            "FileID"         => $fid,
            "FileName"       => $fname,
            "Key"            => $key,
            "FileStream"     => new \CURLFile( public_path( $fpath ) ),
            "ConvertType"    => 'JPG'
            );

        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //删除文件
        unlink($fpath);
        //显示获得的数据
        return json_decode( $data , true);
    }

    //删除文件
    protected function delFile($fid)
    {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, 'http://liveapi1.bell.ai/whiteboardsdk/deletefile');
        //设置头文件的信息作为数据流输出
        // curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        $key = $this->getKey();
        //设置post数据
        $post_data = array(
            "CertificateID"  => $this->cid,
            "FileID"         => $fid,
            "Key"            => $key,
            );

        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return json_decode( $data , true);
    }
}
